<template>
  <div class="role-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2>角色管理</h2>
          <span class="subtitle">管理系统角色及其权限</span>
        </div>
        <el-button type="primary" @click="handleAddRole" class="add-button">
          <el-icon><Plus /></el-icon>新增角色
        </el-button>
      </div>
    </div>

    <!-- 角色列表卡片 -->
    <div class="content-card">
      <!-- 角色列表表格 -->
      <table class="role-table">
        <thead>
          <tr>
            <th>角色ID</th>
            <th>角色名称</th>
            <th>角色描述</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="role in roles" :key="role.rid">
            <td>{{ role.rid }}</td>
            <td>{{ role.rname }}</td>
            <td>{{ role.describes }}</td>
            <td class="actions-column">
              <el-button-group class="action-buttons">
                <el-button type="primary" size="small" @click="handleEditRole(role)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button type="warning" size="small" @click="handleAssignUsers(role)">
                  <el-icon><User /></el-icon>分配
                </el-button>
                <el-button type="danger" size="small" @click="handleDeleteRole(role)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </el-button-group>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 角色编辑对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="580px"
      destroy-on-close
      class="custom-dialog"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <div class="form-header">
          <el-alert
            :title="isEdit ? '修改角色信息' : '创建新的角色'"
            :description="isEdit ? '修改角色的基本信息和描述' : '请填写新角色的基本信息'"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
        <el-form 
          :model="roleForm" 
          :rules="roleRules" 
          ref="roleFormRef" 
          label-width="100px"
          class="role-form"
        >
          <el-form-item label="角色名称" prop="rname">
            <el-input 
              v-model="roleForm.rname" 
              placeholder="请输入角色名称"
              clearable
            >
              <template #prefix>
                <el-icon class="input-icon"><UserFilled /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="describes">
            <el-input
              v-model="roleForm.describes"
              type="textarea"
              :rows="4"
              placeholder="请输入角色描述"
              resize="none"
              show-word-limit
              maxlength="150"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="roleDialogVisible = false" plain>取消</el-button>
          <el-button type="primary" @click="submitRole">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      :title="currentRole?.rname + ' - 权限分配'"
      width="680px"
      destroy-on-close
      class="custom-dialog"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <div class="permission-header">
          <el-alert
            title="权限配置"
            :description="'为角色 ' + currentRole?.rname + ' 分配相应的系统权限'"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
        <div class="permission-toolbar">
          <el-button-group>
            <el-button size="small" @click="handleCheckAll">全选</el-button>
            <el-button size="small" @click="handleUncheckAll">取消全选</el-button>
            <el-button size="small" @click="handleExpandAll">展开/折叠</el-button>
          </el-button-group>
          <el-input
            v-model="permissionSearchKey"
            placeholder="搜索权限"
            clearable
            class="permission-search"
          >
            <template #prefix>
              <el-icon class="input-icon"><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="permission-container">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionsTree"
            show-checkbox
            node-key="p_id"
            :props="{
              label: 'p_name',
              children: 'children'
            }"
            class="permission-tree"
            :filter-node-method="filterNode"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialogVisible = false" plain>取消</el-button>
          <el-button type="primary" @click="submitPermissions">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户分配对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="currentRole?.rname + ' - 用户分配'"
      width="1000px"
      destroy-on-close
      class="custom-dialog user-dialog"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <div class="user-header">
          <el-alert
            title="用户分配"
            :description="'为角色 ' + currentRole?.rname + ' 分配相应的用户'"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
        
        <!-- 用户统计信息 -->
        <div class="user-stats">
          <div class="stat-item">
            <span class="stat-label">已选用户</span>
            <span class="stat-value">{{ selectedUsers.length }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">总可用用户数</span>
            <span class="stat-value">{{ filteredUsers.length }}</span>
          </div>
          <div class="stat-divider"></div>
          <el-button-group>
            <el-button size="small" type="primary" @click="handleSelectAll">
              <el-icon><Select /></el-icon>全选
            </el-button>
            <el-button size="small" @click="handleUnselectAll">
              <el-icon><Remove /></el-icon>清空
            </el-button>
          </el-button-group>
        </div>

        <!-- 搜索 -->
        <div class="user-toolbar">
          <el-input
            v-model="userSearchKey"
            placeholder="搜索用户名或手机号"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon class="input-icon"><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 用户列表 -->
        <div class="user-list-container">
          <div class="user-list">
            <el-checkbox-group v-model="selectedUsers" class="checkbox-list">
              <el-checkbox
                v-for="user in filteredUsers"
                :key="user.uid"
                :label="user.uid"
                :class="{'is-assigned': userRolesMap[user.uid] && userRolesMap[user.uid].includes(currentRole?.rname || '')}"
                class="user-item"
              >
                <div class="user-info">
                  <el-avatar :size="32" class="user-avatar">
                    {{ user.uName.charAt(0).toUpperCase() }}
                  </el-avatar>
                  <div class="user-details">
                    <span class="user-name">{{ user.uName }}</span>
                    <span class="user-phone">{{ user.phone }}</span>
                  </div>
                  <el-tag
                    :type="getUserStatusType(user.usersStatus)"
                    size="small"
                    class="user-status"
                  >
                    {{ getUserStatusText(user.usersStatus) }}
                  </el-tag>
                  <div class="user-roles" v-if="userRolesMap[user.uid] && userRolesMap[user.uid].length > 0">
                    <el-tag
                      v-for="roleName in userRolesMap[user.uid]"
                      :key="roleName"
                      size="small"
                      type="info"
                      effect="plain"
                      class="role-tag"
                    >{{ roleName }}</el-tag>
                  </div>
                </div>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userDialogVisible = false" plain>取消</el-button>
          <el-button type="primary" @click="submitUsers">
            确定 (已选 {{ selectedUsers.length }} 人)
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  Plus,
  Edit,
  Key,
  User,
  Delete,
  UserFilled,
  Search,
  Select,
  Remove
} from '@element-plus/icons-vue'
import { roleApi, userApi } from '../api/console'

interface Role {
  rid: number
  rname: string
  describes: string
}

interface Permission {
  p_id: number
  p_name: string
  p_code: string
  description: string
  children?: Permission[]
}

interface User {
  uid: number
  uName: string
  phone: string
  usersStatus: string
}

interface TreeNode {
  hasChildren: boolean
  expanded: boolean
}

// 状态变量
const loading = ref(false)
const roles = ref<Role[]>([])
const roleDialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const userDialogVisible = ref(false)
const isEdit = ref(false)
const currentRole = ref<Role | null>(null)

// 表单相关
const roleFormRef = ref<FormInstance>()
const roleForm = ref({
  rname: '',
  describes: ''
})
const roleRules = {
  rname: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  describes: [
    { max: 150, message: '最大长度为 150 个字符', trigger: 'blur' }
  ]
}

// 权限树相关
const permissionTreeRef = ref()
const permissionsTree = ref<Permission[]>([])
const permissionSearchKey = ref('')

// 用户分配相关
const userSearchKey = ref('')
const selectedUsers = ref<number[]>([])
const allUsers = ref<{
  uid: number
  uName: string
  phone: string
  usersStatus: string
}[]>([])
const userRolesMap = ref<Record<number, string[]>>({})
const initialSelectedUsers = ref<number[]>([])

// 添加日期相关的变量
const startDate = ref('');
const endDate = ref('');

// 添加用户状态相关方法
const getUserStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': '正常',
    'INACTIVE': '冻结',
    'DELETED': '注销'
  };
  return statusMap[status] || '未知状态';
};

const getUserStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'ACTIVE': 'success',
    'INACTIVE': 'warning',
    'DELETED': 'danger'
  };
  return typeMap[status] || 'info';
};

// 筛选用户列表
const filteredUsers = computed(() => {
  let users = allUsers.value.filter(user => user.usersStatus === 'ACTIVE')

  // 搜索过滤
  if (userSearchKey.value) {
    const searchKey = userSearchKey.value.toLowerCase()
    users = users.filter(user => 
      user.uName.toLowerCase().includes(searchKey) ||
      user.phone.includes(searchKey)
    )
  }

  // 按是否已分配当前角色排序 (已分配的在前)
  users.sort((a, b) => {
    const aHasRole = userRolesMap.value[a.uid]?.includes(currentRole.value?.rname || '');
    const bHasRole = userRolesMap.value[b.uid]?.includes(currentRole.value?.rname || '');
    if (aHasRole && !bHasRole) return -1;
    if (!aHasRole && bHasRole) return 1;
    return 0; // 保持原有顺序
  });

  return users
})

// 重置用户分配相关状态
const resetUserAssignment = () => {
  userSearchKey.value = ''
  selectedUsers.value = []
  initialSelectedUsers.value = []
}

// 权限树过滤方法
const filterNode = (value: string, data: Permission) => {
  if (!value) return true
  return data.p_name.includes(value) || data.p_code.includes(value)
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    loading.value = true
    const response = await roleApi.getRoles()
    
    if (response.code === 200) {
      roles.value = response.data
    } else {
      ElMessage.error(response.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限树
const fetchPermissions = async () => {
  try {
    // TODO: 替换为实际的API调用
    // const response = await fetch('/api/permissions/tree')
    // permissionsTree.value = await response.json()
    
    // 模拟数据
    permissionsTree.value = [
      {
        p_id: 1,
        p_name: '系统管理',
        p_code: 'system',
        description: '系统管理相关权限',
        children: [
          {
            p_id: 2,
            p_name: '用户管理',
            p_code: 'system:users',
            description: '用户管理相关权限'
          },
          {
            p_id: 3,
            p_name: '角色管理',
            p_code: 'system:roles',
            description: '角色管理相关权限'
          }
        ]
      }
    ]
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    const params: Record<string, string> = {};

    // 分别处理开始时间和结束时间
    if (startDate.value) {
      params.startTime = `${startDate.value} 00:00:00`;
    }
    if (endDate.value) {
      params.endTime = `${endDate.value} 23:59:59`;
    }

    if (userSearchKey.value) {
      params.uName = userSearchKey.value.trim();
    }

    const response = await userApi.getUsers(params);

    if (response.code === 200) {
      allUsers.value = response.data.map((user: any) => ({
        ...user,
        uid: user.uId // 统一成 uid
      }));
    } else {
      ElMessage.error(response.message || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
};

// 获取角色的权限
const fetchRolePermissions = async (roleId: number) => {
  try {
    // TODO: 替换为实际的API调用
    // const response = await fetch(`/api/roles/${roleId}/permissions`)
    // const permissions = await response.json()
    
    // 模拟数据
    const permissions = [1, 2] // 权限ID列表
    permissionTreeRef.value?.setCheckedKeys(permissions)
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
  }
}

// 获取所有用户与角色的映射
const fetchAllUserRoles = async () => {
  try {
    const response = await roleApi.getUserRoles()
    if (response.code === 200) {
      // 将返回的数据转换为用户ID到角色名列表的映射
      const map: Record<number, string[]> = {}
      response.data.forEach((item: any) => {
        if (!map[item.uid]) {
          map[item.uid] = []
        }
        map[item.uid].push(item.rname)
      })
      userRolesMap.value = map
    } else {
      ElMessage.error(response.message || '获取用户角色列表失败')
    }
  } catch (error) {
    console.error('获取用户角色列表失败:', error)
    ElMessage.error('获取用户角色列表失败')
  }
}

// 处理新增角色
const handleAddRole = () => {
  isEdit.value = false
  roleForm.value = {
    rname: '',
    describes: ''
  }
  roleDialogVisible.value = true
}

// 处理编辑角色
const handleEditRole = (role: Role) => {
  isEdit.value = true
  currentRole.value = role
  roleForm.value = {
    rname: role.rname,
    describes: role.describes
  }
  roleDialogVisible.value = true
}

// 处理删除角色
const handleDeleteRole = async (role: Role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${role.rname}"吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await roleApi.deleteRole(role.rid)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      await fetchRoles()
    } else {
      ElMessage.error(response.message || '删除角色失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    console.error('删除角色失败:', error)
    ElMessage.error('删除角色失败')
  }
}

// 处理分配权限
const handleAssignPermissions = async (role: Role) => {
  currentRole.value = role
  await fetchPermissions()
  await fetchRolePermissions(role.rid)
  permissionDialogVisible.value = true
}

// 处理分配用户
const handleAssignUsers = async (role: Role) => {
  currentRole.value = role
  resetUserAssignment() // 清空搜索关键字和 selectedUsers
  await fetchUsers() // 获取所有正常用户
  await fetchAllUserRoles() // 获取所有用户角色信息

  // 根据 userRolesMap 初始化 initialSelectedUsers 和 selectedUsers
  if (currentRole.value && allUsers.value.length > 0 && userRolesMap.value) {
    const assignedUsers = allUsers.value
      .filter(user => user.usersStatus === 'ACTIVE' && userRolesMap.value[user.uid]?.includes(currentRole.value?.rname || ''))
      .map(user => user.uid);
    initialSelectedUsers.value = assignedUsers; // 初始化初始已分配用户
    selectedUsers.value = [...assignedUsers]; // 同时初始化当前选中用户列表为已分配用户

    console.log('handleAssignUsers: 初始已分配用户 (initialSelectedUsers):', initialSelectedUsers.value);
    console.log('handleAssignUsers: 初始化选中用户 (selectedUsers):', selectedUsers.value);
  }

  userDialogVisible.value = true
}

// 提交角色表单
const submitRole = async () => {
  if (!roleFormRef.value) return
  
  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (isEdit.value && currentRole.value) {
          // 编辑角色
          response = await roleApi.updateRole(currentRole.value.rid, roleForm.value)
        } else {
          // 新增角色
          response = await roleApi.addRole(roleForm.value)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          roleDialogVisible.value = false
          await fetchRoles()
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新角色失败' : '创建角色失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '更新角色失败:' : '创建角色失败:', error)
        ElMessage.error(isEdit.value ? '更新角色失败' : '创建角色失败')
      }
    }
  })
}

// 提交权限分配
const submitPermissions = async () => {
  if (!currentRole.value || !permissionTreeRef.value) return
  
  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    // TODO: 替换为实际的API调用
    // await fetch(`/api/roles/${currentRole.value.rid}/permissions`, {
    //   method: 'PUT',
    //   body: JSON.stringify({ permissions: checkedKeys })
    // })
    
    ElMessage.success('权限分配成功')
    permissionDialogVisible.value = false
  } catch (error) {
    console.error('分配权限失败:', error)
    ElMessage.error('分配权限失败')
  }
}

// 提交用户分配
const submitUsers = async () => {
  if (!currentRole.value) return

  const currentSelected = selectedUsers.value // 本次操作后的选中用户
  const initialSelected = initialSelectedUsers.value // 打开对话框时的初始已分配用户

  console.log('submitUsers: 当前选中用户 (currentSelected):', currentSelected)
  console.log('submitUsers: 初始已分配用户 (initialSelected):', initialSelected)

  // 计算新增分配和取消分配的用户
  // 用户在 initialSelected 中但不在 currentSelected 中 => 取消分配
  const unassignedUsers = initialSelected.filter(uid => !currentSelected.includes(uid))
  // 用户不在 initialSelected 中但在 currentSelected 中 => 新增分配
  const assignedUsers = currentSelected.filter(uid => !initialSelected.includes(uid))

  console.log('submitUsers: 需要新增分配的用户ID:', assignedUsers)
  console.log('submitUsers: 需要取消分配的用户ID:', unassignedUsers)

  try {
    // 调用分配角色的接口
    const assignPromises = assignedUsers.map(uId =>
      roleApi.assignRole(uId, currentRole.value!.rid)
    )

    // 调用删除角色的接口
    const unassignPromises = unassignedUsers.map(uId =>
      roleApi.removeRole(uId, currentRole.value!.rid)
    )

    // 等待所有接口调用完成
    await Promise.all([...assignPromises, ...unassignPromises])

    let successMessage = ''
    if (assignedUsers.length > 0 && unassignedUsers.length > 0) {
      successMessage = `成功分配 ${assignedUsers.length} 人，解除 ${unassignedUsers.length} 人。`
    } else if (assignedUsers.length > 0) {
      successMessage = `成功分配 ${assignedUsers.length} 人。`
    } else if (unassignedUsers.length > 0) {
      successMessage = `成功解除 ${unassignedUsers.length} 人。`
    } else {
      successMessage = '没有进行任何用户分配或取消操作。'
    }

    ElMessage.success(successMessage)

    userDialogVisible.value = false

  } catch (error) {
    console.error('分配/解除用户角色失败:', error)
    ElMessage.error('分配/解除用户角色失败')
  }
}

// 权限树操作
const handleCheckAll = () => {
  const allKeys = getAllKeys(permissionsTree.value)
  permissionTreeRef.value?.setCheckedKeys(allKeys)
}

const handleUncheckAll = () => {
  permissionTreeRef.value?.setCheckedKeys([])
}

const handleExpandAll = () => {
  // 获取当前展开状态的第一个节点
  const firstNode = permissionTreeRef.value?.store.nodesMap[permissionsTree.value[0].p_id] as TreeNode | undefined
  const isExpanded = firstNode?.expanded
  
  // 遍历所有节点，设置相反的展开状态
  const allNodes = permissionTreeRef.value?.store.nodesMap as Record<string, TreeNode> | undefined
  if (allNodes) {
    Object.values(allNodes).forEach(node => {
      if (node.hasChildren) {
        node.expanded = !isExpanded
      }
    })
  }
}

// 获取所有权限的ID
const getAllKeys = (permissions: Permission[]): number[] => {
  const keys: number[] = []
  const traverse = (items: Permission[]) => {
    items.forEach(item => {
      keys.push(item.p_id)
      if (item.children) {
        traverse(item.children)
      }
    })
  }
  traverse(permissions)
  return keys
}

// 监听权限搜索关键字变化
watch(permissionSearchKey, (val) => {
  permissionTreeRef.value?.filter(val)
})

// 全选/清空操作
const handleSelectAll = () => {
  selectedUsers.value = filteredUsers.value
    .filter(user => user.usersStatus === 'ACTIVE')
    .map(user => user.uid);
};

const handleUnselectAll = () => {
  selectedUsers.value = [];
};

// 生命周期钩子
onMounted(async () => {
  await fetchRoles()
})
</script>

<style scoped>
.role-management {
  min-height: 100vh;
  background-color: #f0f2f5;
  padding: 20px;
  margin-left: 200px;
  margin-top: 45px;
  width: calc(100% - 200px); /* 减去sidebar的宽度 */
  box-sizing: border-box; /* 确保padding不会增加总宽度 */
}

.page-header {
  background: #fff;
  padding: 16px 24px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  display: flex;
  flex-direction: column;
}

.title-section h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #1f2937;
}

.subtitle {
  margin-top: 4px;
  font-size: 14px;
  color: #6b7280;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.content-card {
  background: #fff;
  padding: 24px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  width: 100%;
  box-sizing: border-box;
  overflow-x: auto; /* 添加横向滚动 */
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  width: 100%;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0;
}

/* 自定义对话框样式 */
.custom-dialog {
  border-radius: 8px;
}

:deep(.el-dialog) {
  --el-dialog-border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 24px;
  border-bottom: 1px solid var(--el-border-color-light);
  flex-shrink: 0;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

:deep(.el-dialog__body) {
  padding: 0;
  overflow-y: auto;
  flex: 1;
}

:deep(.el-dialog__footer) {
  margin: 0;
  padding: 16px 24px;
  border-top: 1px solid var(--el-border-color-light);
  flex-shrink: 0;
}

.dialog-content {
  padding: 24px;
}

.form-header,
.permission-header,
.user-header {
  margin-bottom: 24px;
}

/* 表单样式 */
.role-form {
  margin-top: 24px;
}

.role-form :deep(.el-form-item__label) {
  font-weight: 500;
}

.input-icon {
  color: var(--el-text-color-secondary);
}

/* 权限树相关样式 */
.permission-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 16px;
}

.permission-search {
  width: 220px;
}

.permission-container {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  height: 400px;
  overflow: hidden;
}

.permission-tree {
  height: 100%;
  padding: 16px;
  overflow-y: auto;
}

/* 用户分配对话框样式 */
.user-dialog :deep(.el-dialog__body) {
  padding: 0;
  overflow-y: auto;
}

.user-stats {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  margin: 16px 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 24px;
}

.stat-label {
  font-size: 13px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.stat-divider {
  width: 1px;
  height: 32px;
  background-color: var(--el-border-color);
  margin: 0 16px;
}

.user-toolbar {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.search-input {
  width: 240px;
}

.user-list-container {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  height: 340px;
  overflow: hidden;
}

.user-list {
  height: 100%;
  overflow-y: auto;
}

.checkbox-list {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.user-item {
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-light);
  margin: 0 !important;
  display: flex;
  align-items: center;
  cursor: pointer !important;
}

.user-item.is-assigned {
  background-color: #f5f5f5; /* 浅灰色背景 */
}

.user-item .user-info {
  flex: 1; /* 让 user-info 占据剩余空间，将标签推到右边 */
  display: flex; /* 使用 flex 布局 */
  align-items: center; /* 垂直居中对齐 */
}

.user-item .user-info .user-details {
  flex: 1; /* 让 user-details 占据 user-info 的剩余空间 */
}

.user-item:last-child {
  border-bottom: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: 8px;
}

.user-avatar {
  background-color: var(--el-color-primary);
  color: white;
  font-weight: bold;
}

.user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.user-phone {
  font-size: 13px;
  color: var(--el-text-color-secondary);
  margin-top: 2px;
}

.user-status {
  margin-left: auto;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .role-management {
    margin-left: 0;
    width: 100%;
    padding: 10px;
  }

  .page-header {
    padding: 12px 16px;
  }

  .content-card {
    padding: 16px;
    overflow-x: auto;
  }

  .role-table {
    min-width: 800px;
  }

  .header-content {
    flex-direction: column;
    gap: 16px;
  }

  .title-section {
    width: 100%;
    text-align: center;
  }

  .add-button {
    width: 100%;
    justify-content: center;
  }

  .action-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }

  .action-buttons .el-button {
    margin: 4px;
  }
}

.role-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.role-table th,
.role-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
  color: #333;
  vertical-align: middle;
}

.role-table th {
  background-color: #f2f2f2;
  font-weight: bold;
  color: #333;
}

.role-table tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.role-table tbody tr:hover {
  background-color: #f5f5f5;
}

.actions-column {
  white-space: nowrap;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 200px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  width: 100%;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0;
}
</style> 